import { useEffect, useRef, useState } from 'react';
import { Form, Input, Button, message, Card } from 'antd';
import { connect, useIntl } from 'umi';
import request from '@/utils/request';

const apiURL = '/api/services/app/SysConfig/';

const SyscfgEdit = (props: any) => {
  const [loading, setLoading] = useState(false);
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    const { tenantid } = props;
    if (tenantid) {
      getData(tenantid);
    }
  }, [props.tenantid]);

  const getData = (tenantid: number) => {
    request(apiURL + 'GetByTId', {
      method: 'GET',
      params: {
        tenantid,
      },
    }).then((response) => {
      if (response.success && response.result) {
        formRef.current.setFieldsValue(response.result);
      } else {
        message.warning(intl.formatMessage({ id: 'pages.sysconfig.noexist' }));
      }
    });
  };

  const onFinish = (values: any) => {
    setLoading(true);
    request(apiURL + 'UpdateTenantVersion', {
      method: 'PUT',
      params: {
        tenantid: props.tenantid,
        version: values.version,
      },
    }).then((response) => {
      if (response.success) {
        message.success(intl.formatMessage({ id: 'pages.updateVersion.success' }));
      }
      setLoading(false);
    });
  };

  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  };

  return (
    <Form {...layout} ref={formRef} layout="horizontal" onFinish={onFinish}>
      <Card bordered={false}>
        <Form.Item name="companyName" label={intl.formatMessage({ id: 'pages.company' })}>
          <Input disabled />
        </Form.Item>
        <Form.Item name="version" label={intl.formatMessage({ id: 'pages.productVersion' })}>
          <Input />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: layout.labelCol.span }}>
          <Button type="primary" htmlType="submit" loading={loading}>
            {intl.formatMessage({ id: 'pages.ok' })}
          </Button>
        </Form.Item>
      </Card>
    </Form>
  );
};

export default connect(({ user }: API.IConnectState) => ({
  currentUser: user.currentUser,
}))(SyscfgEdit);
